<template>
  <base-dialog destroy-on-close show-footer :title="modalTitle" @close="handleHide" v-model="modalShow" :width="700">
    <el-form ref="addFormRef" :model="addForm" :rules="rules" label-width="auto" label-position="top">
      <el-form-item label="上级分类" v-if="modalType !== 'add' && currentInfo && currentInfo.classificationType !== 1">
        {{ currentInfo.superiorClassificationName || "" }}
      </el-form-item>
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="addForm.name" placeholder="请输入分类名称" :maxlength="6" />
      </el-form-item>
      <el-form-item label="分类图片" prop="imgUrl">
        <el-upload
          ref="uploadRef"
          class="avatar-uploader"
          action="#"
          :limit="2"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleBeforeUpload"
          accept=".png,.jpeg,.jpg"
        >
          <div class="upload-btn">
            <img class="class-img" v-if="addForm.imgUrl" :src="addForm.imgUrl" />
            <base-icon v-else name="iconfont ic-yunshangchuan" :size="30" />
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="分类标签" prop="cateLabel">
        <div class="tag-input">
          <el-input v-model="addForm.cateLabel" placeholder="请输入5个字以内的标签名称" :maxlength="5" />
          <el-button class="tag-input-btn" link type="primary" @click="showExample"
            >查看示例<base-icon name="iconfont ic-xiajiantou1" :size="14" />
          </el-button>
        </div>
      </el-form-item>
      <el-form-item label="排列序号" prop="sortNo">
        <el-input v-model="addForm.sortNo" placeholder="请输入排列序号" />
      </el-form-item>
      <el-form-item label="支付宝类目" prop="zfbCode">
        <el-input v-model="addForm.zfbCode" placeholder="请输入支付宝类目" :maxlength="50" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :plain="true" class="btn--rect" @click="handleHide"> 取消 </el-button>
      <el-button type="primary" class="btn--rect" @click="handleConfirmAdd"> 确认 </el-button>
    </template>
    <base-dialog v-model="dialogVisible" title="查看标签示例" width="500" :show-footer="false">
      <img src="@/assets/product/class-example.png" class="example-img" />
    </base-dialog>
  </base-dialog>
</template>

<script setup>
  // props
  const props = defineProps({
    show: { type: Boolean, default: false },
    currentInfo: {
      type: Object,
      default: () => {
        return {};
      },
    },
    // 弹窗类型
    modalType: { type: String, default: "add" },
  });
  const emit = defineEmits(["hide", "confirm"]);
  // 监听显隐
  watch(
    () => props.show,
    v => {
      modalShow.value = v;
      if (props.show) {
        init();
      }
    }
  );
  // 显示、隐藏
  const modalShow = ref(props.show);
  // 示例弹窗
  const dialogVisible = ref(false);
  // 表单Ref
  const addFormRef = ref();
  // 表单内容
  const addForm = reactive({
    name: "",
    imgUrl: "",
    sortNo: "",
    zfbCode: "",
    cateLabel: "",
  });
  // 表单规则
  const rules = reactive({
    name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
    imgUrl: [{ required: true, message: "请上传分类图片", trigger: "change" }],
    sortNo: [{ required: true, message: "请输入排列序号", trigger: "blur" }],
    zfbCode: [{ required: true, message: "请输入支付宝类目", trigger: "blur" }],
  });
  // 标题
  const modalTitle = computed(() => {
    if (props.modalType === "add") {
      return props.currentInfo && props.currentInfo?.classificationType === 1
        ? "新增二级分类"
        : props.currentInfo && props.currentInfo?.classificationType === 2
          ? "新增三级分类"
          : "新增一级分类";
    } else {
      return props.currentInfo && props.currentInfo?.classificationType === 1
        ? "编辑二级分类"
        : props.currentInfo && props.currentInfo?.classificationType === 2
          ? "编辑三级分类"
          : "编辑一级分类";
    }
  });
  // 上传Ref
  const uploadRef = ref(null);
  // 初始化
  const init = () => {
    if (props.modalType === "edit") {
      const { name, imgUrl, sortNo, zfbCode, cateLabel } = props.currentInfo;
      Object.assign(addForm, {
        name,
        imgUrl,
        sortNo,
        zfbCode,
        cateLabel,
      });
    }
  };
  // 文件上传
  const handleUpload = file => {
    const formData = new FormData();
    formData.append("file", file);
    Api.common.fileUpload(formData).then(res => {
      addForm.imgUrl = res.data;
      nextTick(() => {
        uploadRef.value.clearFiles();
      });
    });
  };
  // 上传前处理
  const handleBeforeUpload = rawFile => {
    if (!["image/png", "image/jpeg", "image/jpg"].includes(rawFile.raw.type)) {
      $msg.error("请上传jpeg/jpg/png格式图片");
      return false;
    } else if (rawFile.raw.size / 1024 / 1024 > 2) {
      $msg.error("上传图片最大不超过2MB!");
      return false;
    }
    handleUpload(rawFile.raw);
    return true;
  };
  // 确认添加
  const handleConfirmAdd = () => {
    addFormRef.value.validate(err => {
      if (!err) {
        return;
      }
      // 分类参数
      const params = {
        ...addForm,
      };
      // 新增一级、二级、三级、分类
      if (props.modalType === "add") {
        // 类目层级
        if (props.currentInfo && props.currentInfo.classificationType === 1) {
          // 二级
          params["classificationType"] = 2;
        } else if (props.currentInfo && props.currentInfo.classificationType === 2) {
          // 三级
          params["classificationType"] = 3;
        } else {
          // 一级
          params["classificationType"] = 1;
        }
        // 设置父级ID
        if (params.classificationType === 1) {
          params["parentId"] = 0;
        } else {
          params["parentId"] = props.currentInfo.id;
        }
        Api.product.addClassification(params).then(() => {
          $msg.success("新增成功");
          handleHide(true);
        });
      } else {
        params["classificationType"] = props.currentInfo.classificationType;
        params["parentId"] = props.currentInfo.parentId;
        params["id"] = props.currentInfo.id;
        // 编辑
        Api.product.editClassification(params).then(() => {
          $msg.success("操作成功");
          handleHide(true);
        });
      }
    });
  };
  // 关闭
  const handleHide = isRefresh => {
    Object.assign(addForm, {
      name: "",
      imgUrl: "",
      sortNo: "",
      zfbCode: "",
      cateLabel: "",
    });
    emit("hide", isRefresh);
  };
  // 显示示例
  const showExample = () => {
    dialogVisible.value = true;
  };
</script>

<style lang="scss" scoped>
  .avatar-uploader {
    width: 100px;
    height: 100px;
    border: 1px dashed #ccc;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 30px;
    .upload-btn {
      width: 100px;
      height: 100px;
      display: flex;
      align-items: center;
      justify-content: center;
      .class-img {
        width: 100%;
        height: 100%;
      }
    }
  }
  .tag-input {
    position: relative;
    width: 100%;
    .tag-input-btn {
      position: absolute;
      right: 0;
      top: -25px;
    }
  }
  .example-img {
    width: 100%;
  }
</style>
